package com.shop.cereshop.admin.job;

import com.shop.cereshop.commons.constant.RedisConstants;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

@Component
@Order(9)
@Slf4j
public class OnlineJob {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 定时清理过期的在线用户
     * 每5分钟执行一次
     */
    @XxlJob("cleanExpiredOnlineUsers")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void cleanExpiredOnlineUsers() {
        try {
            System.out.println("成功开始清理过期在线用户定时任务");
            // 先获取即将过期的用户ID，用于后续清理用户信息
            String getExpiredUsersScript = "local current_time = tonumber(ARGV[1])\n" +
                    "if not current_time then\n" +
                    "    return {} -- 如果转换失败，返回空列表\n" +
                    "end\n" +
                    "local expired_users = redis.call('ZRANGEBYSCORE', KEYS[1], 0, current_time)\n" +
                    "redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, current_time)\n" +
                    "return expired_users";



            List<String> keys = Collections.singletonList(RedisConstants.ONLINE_USER_KEY);
            List<String> args = Collections.singletonList(String.valueOf(System.currentTimeMillis()));

            List<String> expiredUsers = (List<String>) redisTemplate.execute(
                    new DefaultRedisScript<>(getExpiredUsersScript, List.class),
                    keys,
                    args.toArray()
            );

            // 清理过期用户的详细信息
            if (expiredUsers != null && !expiredUsers.isEmpty()) {
                // 从Hash中删除过期用户的字段
                redisTemplate.opsForHash().delete(RedisConstants.USER_INFO_PREFIX, expiredUsers.toArray());
                
                XxlJobHelper.log("清理了 {} 个过期的在线用户，包括详细信息", expiredUsers.size());
                log.info("清理了 {} 个过期的在线用户，包括详细信息", expiredUsers.size());
            } else {
                XxlJobHelper.log("没有需要清理的过期在线用户");
                log.info("没有需要清理的过期在线用户");
            }
        } catch (Exception e) {
            XxlJobHelper.handleFail("清理过期在线用户失败: " + e.getMessage());
            log.error("清理过期在线用户失败", e);
        }
    }
}
